const jwt = require('jsonwebtoken')

/** 捕获异常 */
const handler = async (ctx, next) => {
    try {
        await next();
    } catch (err) {
        ctx.response.status = err.statusCode || err.status || 500;
        // ctx.response.body = global.toJson(500, '系统出问题了，请联系开发人员修复');
        ctx.response.body = global.toJson(500, err);
        ctx.app.emit('error', err, ctx);
    }
};
const author = function (ctx, next) {
    if(ctx.header.authorization){
        const token = ctx.header.authorization.split(' ')[1]
        jwt.verify(token, 'see_you', (err, decoded) => {
            if(err) return ctx.response.body = global.toJson(401, 'token信息错误')
            global.utils.PersonInfo = decoded // 返回用户信息
        })
    }
    return next().catch((err) => {
        if (err.status === 401) {
            ctx.status = 401;
            ctx.body =  global.toJson(401, '权限不足，请重新登录')
        } else {
            throw err;
        }
    });
}
module.exports ={ handler: handler, author: author }
